<template>
  <Modal v-model="modal" class="chat" @on-cancel="onCancel" :width="800" title="聊天室">
    <div class="content">
      <ul class="ul">
        <li v-for="(item, index) of list" :key="index" :class="[userInfo.id == item.user_id ? 'right': 'left', !item.creation_time ?  'center1': 'de']">
          <span v-if="item.headimage" class="circle">
            <img  class="circle-img" :src="item.headimage" alt="">
          </span>
          <span v-if="!item.headimage" class="circle">
            <img class="circle-img" :src="default1" alt="">
          </span>
          <!-- {{item}} -->
          <div class="set-content">
            <div class="username">{{item.user_name}}  {{item.creation_time}}</div>
            <span class="text" v-if="item.type == 1">{{item.content}}</span>
            <viewer :images="(item.content && item.content.split(','))" v-else-if="item.type == 2"> 
                <img class="text1" v-for="(todo, index) of (item.content && item.content.split(','))" :key="index" :src="todo" alt="">
            </viewer>
            <FileLoad v-else-if="item.type == 3" :info="item"></FileLoad>
            <VideoLoad v-else-if="item.type == 4" :info="item"></VideoLoad>
          </div>
        </li>
      </ul>
    </div>
    <div slot="footer">
      <slot name="file"></slot>
      <slot name="img"></slot>
      <Input v-model="value" type="textarea" style="width: 550px" @on-enter="send_message()" />
      <Button type="primary" size="large" :disabled="disabled" @click="send_message()">发送</Button>
    </div>
  </Modal>
</template>
<script>
import { mapGetters } from 'vuex'
import FileLoad  from '@/components/FileLoad'
import VideoLoad from '@/components/VideoLoad'
export default {
  components: {
    FileLoad,
    VideoLoad
  },
  data() {
    return {
      modal: false,
      order_id: 28,
      value: '',
      list: [{}],
      socket: '',
      // 新加
      timeout: 2000,
      timeoutObj: null,
      serverTimeoutObj: null,
      lockReconnect: false,
      wsUrl: 'wss://www.yybxk.net/chat', // 'ws://139.196.141.25:9502',
      default1: require("../assets/images/default.jpeg")
    }
  },
  mounted() {
  },
  methods: {
    createWebSocket() {
        try{
            if('WebSocket' in window){
                this.socket = new WebSocket(this.wsUrl);
            }
            // initEventHandle();
            // this.init()
        }catch(e){
            reconnect(url);
            console.log(e);
        }
    },
    //心跳检测
    heartCheck() {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        var self = this;
        this.timeoutObj = setTimeout(function(){
          // console.log("dnqoi1")
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            self.socket.send("ping");
            console.log("ping!")
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
                console.log("我很无语")
                self.socket.close();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, self.timeout)
    },
    reconnect(url) {
        let self = this
        if(this.lockReconnect) return;
        this.lockReconnect = true;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            console.log("进来没")
            // self.createWebSocket(this.wsUrl);
            self.init()
            self.lockReconnect = false;
        }, 2000);
    },
    open(item) {
      this.list = []
      this.modal = true
      this.order_id = item.order_id
      this.getData()
    },
    getData() {
      this.$ajaxGet("/order/talkRecord", {order_id: this.order_id}).then(res => {
        this.list = res
        this.init()
        this.onScroll()
      })
    },
    // 发送按钮
    send_message(data){
      // this.value = ''
      // type 1 文字 2图片
      let type = 1
      let message = ''
      if (data !== undefined) {
        type = data.type
        if (type == 3) {
          message = data.file
        } else {
          message = data.file
        }
      }
      let ob = ''
      if (type == 1) {
        ob = JSON.stringify({ message: this.value,
          order_id: this.order_id,
          user_id: this.userInfo.id,
          type: 1,headimage: this.userInfo.avatar,
          user_name: this.userInfo.userName
        });
      } else if (type == 2){
        ob = JSON.stringify({ 
          message: message, 
          order_id: this.order_id, 
          user_id: this.userInfo.id,
          type: 2,
          headimage: this.userInfo.avatar,
          user_name: this.userInfo.userName 
        });
      } else if (type == 3) {
        ob = JSON.stringify({ 
          message: message, 
          order_id: this.order_id, 
          user_id: this.userInfo.id,
          type: 3,
          headimage: this.userInfo.avatar,
          user_name: this.userInfo.userName ,
          name: data.name
        });
      } else if (type == 4) {
        ob = JSON.stringify({ 
          message: message, 
          order_id: this.order_id, 
          user_id: this.userInfo.id,
          type: 4,
          headimage: this.userInfo.avatar,
          user_name: this.userInfo.userName ,
          name: data.name
        });
      }
      console.log(ob)
      this.socket.send(ob);
    },
    updated(data) {
      if (data.data == 'ping' || data.data == 'Opened') {
      } else {
        console.log(data)
        let pose = data
        let res = ''
        if (pose.data !== undefined) res = JSON.parse(pose.data)
        if (res.msg !== undefined) {
          let msg = JSON.parse(res.msg)
          // debugger
          // 不是本订单return
          if (msg.order_id != this.order_id) return
          // 查出对象中有 fdId 并保存这个值
          if (msg.hasOwnProperty('fdId') && msg.type == 'storage') {
            window.fdId = msg.fdId
          }
          if (this.userInfo.id === msg.user_id && (window.fdId && window.fdId !==  Number(res.fd))) return
          console.log(window.fdId)
          this.list.push({
            user_id: msg.user_id,
            order_id: msg.order_id,
            content: msg.message,
            type: msg.type,
            headimage: msg.headimage, 
            user_name: msg.user_name,
            name: msg.name
          })
          // if(msg.type == 4) {
            this.$nextTick(()=> {
              this.onScroll()
            })
          // }
          this.value = ''
        } else {
          // debugger
          if (res.hasOwnProperty('fdId')) {
            window.fdId = res.fdId
          }
          if (res.order_id !== this.order_id) return
          this.list.push({
            user_id: res.user_id,
            order_id: res.order_id,
            content: res.message,
            type: res.type,
            headimage: res.headimage, 
            user_name: res.user_name,
            name: res.name
          })
          this.$nextTick(()=> {
            this.onScroll()
          })
        }
      }
    },
    init() {
      this.createWebSocket()
      this.socket.onopen =  () => {
        this.socket.send(JSON.stringify({order_id: this.order_id}));
        this.heartCheck();      //心跳检测重置
        console.log("llws连接成功1!"+new Date().toLocaleString());
      };
      this.socket.onmessage = (data) => {
        this.updated(data)
        this.heartCheck(); 
      };
      this.socket.onclose =  () => {
        // this.reconnect();
        console.log("llws连接关闭!"+new Date().toLocaleString());
      };
      this.socket.onerror =  () => {
        // debugger
        this.reconnect();
        console.log("llws连接错误!");
      };
    },
    onCancel() {
      this.socket.close()
    },
    // 滚动条滑动到底部
    onScroll() {
      let target = document.querySelector('.ul')
      console.log(target.scrollHeight)
      this.$nextTick(() => {
        target.scrollTop = target.scrollHeight
      })
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  }
}
</script>